package io.renren.wechat.service.department;

import io.renren.wechat.common.WechatResponse;
import io.renren.wechat.service.domain.CreateDeptResponse;
import io.renren.wechat.service.domain.Department;
import io.renren.wechat.service.domain.DepartmentList;
import io.renren.wechat.service.suite.SuiteService;
import io.renren.wechat.service.token.AccessTokenService;
import io.renren.wechat.support.WechatConstants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Component
public class DepartmentService {
    private static final Logger LOGGER = LoggerFactory.getLogger(DepartmentService.class);

    private AccessTokenService accessTokenService;
    private RestTemplate fastRestTemplate;
    private SuiteService suiteService;

    /**
     * 创建部门
     *
     * @param department creating dept info
     * @link https://open.work.weixin.qq.com/api/doc/90000/90135/90205
     */
    public Integer create(String corpId, Department department) {
        final String accessToken = suiteService.getAuthCorpAccessToken(corpId, 0);
        String createDeptUrl = String.format(WechatConstants.DEPARTMENT_CREATE_URL, accessToken);

        final ResponseEntity<CreateDeptResponse> responseEntity = fastRestTemplate.postForEntity(createDeptUrl, department, CreateDeptResponse.class);
        LOGGER.debug("create dept response entity: {}", responseEntity);

        final CreateDeptResponse entityBody = responseEntity.getBody();
        if (!responseEntity.getStatusCode().is2xxSuccessful() || entityBody == null) {
            LOGGER.warn("response code: {}", responseEntity.getStatusCodeValue());
            throw new RuntimeException("创建部门失败");
        }

        if (!entityBody.isSuccess()) {
            LOGGER.warn("创建部门失败, errMsg: {}", entityBody.getErrmsg());
            throw new RuntimeException("创建部门失败: " + entityBody.getErrmsg());
        }

        return entityBody.getId();
    }

    /**
     * 更新部门
     *
     * @param department updating dept info
     * @return
     * @link https://open.work.weixin.qq.com/api/doc/90000/90135/90206
     */
    public void update(String corpId, Department department) {
        if (department.getId() == null) {
            throw new IllegalArgumentException("dept id is required.");
        }
        final String accessToken = suiteService.getAuthCorpAccessToken(corpId, 0);
        String updateDeptUrl = String.format(WechatConstants.DEPARTMENT_UPDATE_URL, accessToken);

        final ResponseEntity<WechatResponse> responseEntity = fastRestTemplate.postForEntity(updateDeptUrl, department, WechatResponse.class);
        LOGGER.debug("update dept response entity: {}", responseEntity);

        final WechatResponse entityBody = responseEntity.getBody();
        if (!responseEntity.getStatusCode().is2xxSuccessful() || entityBody == null) {
            LOGGER.warn("response code: {}", responseEntity.getStatusCodeValue());
            throw new RuntimeException("创建部门失败");
        }

        if (!entityBody.isSuccess()) {
            LOGGER.warn("创建部门失败, errMsg: {}", entityBody.getErrmsg());
            throw new RuntimeException("创建部门失败: " + entityBody.getErrmsg());
        }
    }

    /**
     * 删除部门
     *
     * @param deptId 部门id。（注：不能删除根部门；不能删除含有子部门、成员的部门）
     * @link https://open.work.weixin.qq.com/api/doc/90000/90135/90207
     */
    public void delete(String corpId, Integer deptId) {
        if (deptId == null) {
            throw new IllegalArgumentException("dept id is required.");
        }
        final String accessToken = suiteService.getAuthCorpAccessToken(corpId, 0);
        String deleteDeptUrl = String.format(WechatConstants.DEPARTMENT_DELETE_URL, accessToken, deptId);

        final ResponseEntity<WechatResponse> responseEntity = fastRestTemplate.getForEntity(deleteDeptUrl, WechatResponse.class);
        LOGGER.debug("delete dept response entity: {}", responseEntity);

        final WechatResponse entityBody = responseEntity.getBody();
        if (!responseEntity.getStatusCode().is2xxSuccessful() || entityBody == null) {
            LOGGER.warn("response code: {}", responseEntity.getStatusCodeValue());
            throw new RuntimeException("删除部门失败");
        }

        if (!entityBody.isSuccess()) {
            LOGGER.warn("删除部门失败, errMsg: {}", entityBody.getErrmsg());
            throw new RuntimeException("删除部门失败: " + entityBody.getErrmsg());
        }
    }

    /**
     * 获取部门列表
     *
     * @param departmentId 部门id。获取指定部门及其下的子部门（以及及子部门的子部门等等，递归）。如果不填，默认获取全量组织架构
     * @return 部门列表
     * @link https://open.work.weixin.qq.com/api/doc/90000/90135/90208
     */
    public List<Department> list(String corpId, Integer departmentId) {
        if (StringUtils.isBlank(corpId)) {
            throw new RuntimeException("corpId是必须的");
        }
        final String accessToken = suiteService.getAuthCorpAccessToken(corpId, 0);

        //final String accessToken = accessTokenService.getAccessToken();
        String getDepartmentListUrl = String.format(WechatConstants.DEPARTMENT_LIST_URL, accessToken);
        if (departmentId != null) {
            getDepartmentListUrl += "&id=" + departmentId;
        }

        final ResponseEntity<DepartmentList> responseEntity = fastRestTemplate.getForEntity(getDepartmentListUrl, DepartmentList.class);
        LOGGER.debug("response entity: {}", responseEntity);

        final DepartmentList entityBody = responseEntity.getBody();
        if (!responseEntity.getStatusCode().is2xxSuccessful() || entityBody == null) {
            LOGGER.warn("response code: {}", responseEntity.getStatusCodeValue());
            throw new RuntimeException("获取部门列表失败");
        }

        if (!entityBody.isSuccess()) {
            LOGGER.warn("获取部门列表失败, errMsg: {}", entityBody.getErrmsg());
            throw new RuntimeException("获取部门列表失败");
        }

        return entityBody.getDepartment();
    }

    @Autowired
    public void setAccessTokenService(AccessTokenService accessTokenService) {
        this.accessTokenService = accessTokenService;
    }

    @Autowired
    public void setFastRestTemplate(RestTemplate fastRestTemplate) {
        this.fastRestTemplate = fastRestTemplate;
    }

    @Autowired
    public void setSuiteService(SuiteService suiteService) {
        this.suiteService = suiteService;
    }
}
